#!/bin/bash

# MySQL 数据库初始化脚本
# 用法: ./dev_init_mysql.sh [环境] [db_host] [db_port] [root密码] [可选: 应用用户名] [可选: 应用用户密码]
# 示例: ./script/dev_init_mysql.sh development 127.0.0.1 3306 root flask flask@123
set -e  # 遇到错误立即退出

# 颜色输出定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示用法
usage() {
    echo "用法: $0 [环境] [db_host] [db_port] [root密码] [可选: 应用用户名] [可选: 应用用户密码]"
    echo "环境: development 或 production"
    echo "示例: $0 ./script/dev_init_mysql.sh development 127.0.0.1 3306 root flask flask@123"
    exit 1
}

# 检查参数
if [ $# -lt 2 ]; then
    usage
fi

ENVIRONMENT=$1
HOST=$2
PORT=$3
ROOT_PASSWORD=$4
APP_USER=${5:-string_generator_user}
APP_PASSWORD=${6:-$(openssl rand -base64 12)}  # 生成随机密码

# 验证环境参数
if [ "$ENVIRONMENT" != "development" ] && [ "$ENVIRONMENT" != "production" ]; then
    log_error "环境参数必须是 'development' 或 'production'"
    exit 1
fi

# 设置数据库名称
if [ "$ENVIRONMENT" = "development" ]; then
    DB_NAME="string_generator_dev"
else
    DB_NAME="string_generator"
fi

log_info "开始初始化 $ENVIRONMENT 环境的 MySQL 数据库"

# 检查 MySQL 地址是否可达
if command -v nc &> /dev/null; then
    echo "使用 nc (netcat) 检查"
    if nc -z -w 5 "$HOST" "$PORT" 2>/dev/null; then
        echo "✅ 连接成功: $HOST:$PORT 可达"
    else
        echo "❌ 连接失败: $HOST:$PORT 不可达"
        exit 0
    fi
fi

# 创建 SQL 命令文件
SQL_FILE="/tmp/init_mysql_${ENVIRONMENT}.sql"
cat > "$SQL_FILE" << EOF
-- 创建数据库
CREATE DATABASE IF NOT EXISTS ${DB_NAME} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建应用用户并授予权限
CREATE USER IF NOT EXISTS '${APP_USER}'@'%' IDENTIFIED BY '${APP_PASSWORD}';
GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${APP_USER}'@'%';
GRANT SELECT, INSERT, UPDATE, DELETE ON ${DB_NAME}.* TO '${APP_USER}'@'%';

-- 刷新权限
FLUSH PRIVILEGES;

-- 显示创建的用户和数据库
SELECT User, Host FROM mysql.user WHERE User = '${APP_USER}';
SHOW DATABASES LIKE '${DB_NAME}';
EOF

log_info "执行 SQL 命令初始化数据库..."

# 执行 SQL 命令
mysql -u root -h "${HOST}" -P "${PORT}" -p"${ROOT_PASSWORD}" < "$SQL_FILE"

if [ $? -eq 0 ]; then
    log_info "MySQL 数据库初始化成功!"
    log_info "数据库名称: ${DB_NAME}"
    log_info "应用用户名: ${APP_USER}"
    log_info "应用用户密码: ${APP_PASSWORD}"

    # 更新环境文件
    ENV_FILE=".env"
    if [ -f "$ENV_FILE" ]; then
        # 更新或添加数据库连接字符串
        if [ "$ENVIRONMENT" = "development" ]; then
            sed -i "" "/DEV_DATABASE_URL/d" "$ENV_FILE"
            echo "DEV_DATABASE_URL=mysql+pymysql://${APP_USER}:${APP_PASSWORD}@localhost/${DB_NAME}?charset=utf8mb4" >> "$ENV_FILE"
        else
            sed -i "" "/DATABASE_URL/d" "$ENV_FILE"
            echo "DATABASE_URL=mysql+pymysql://${APP_USER}:${APP_PASSWORD}@localhost/${DB_NAME}?charset=utf8mb4" >> "$ENV_FILE"
        fi
        log_info "已更新 $ENV_FILE 文件"
    else
        log_warning ".env 文件不存在，创建新文件"
        cat > "$ENV_FILE" << EOF
FLASK_APP=manage.py
FLASK_ENV=development
SECRET_KEY=your-secret-key-change-in-production
EOF
        if [ "$ENVIRONMENT" = "development" ]; then
            echo "DEV_DATABASE_URL=mysql+pymysql://${APP_USER}:${APP_PASSWORD}@localhost/${DB_NAME}?charset=utf8mb4" >> "$ENV_FILE"
        else
            echo "DATABASE_URL=mysql+pymysql://${APP_USER}:${APP_PASSWORD}@localhost/${DB_NAME}?charset=utf8mb4" >> "$ENV_FILE"
        fi
    fi

    # 显示连接信息
    echo ""
    log_info "连接信息:"
    echo "数据库: ${DB_NAME}"
    echo "用户名: ${APP_USER}"
    echo "密码: ${APP_PASSWORD}"
    echo "主机: localhost"
    echo "字符集: utf8mb4"

else
    log_error "MySQL 数据库初始化失败!"
    exit 1
fi

# 清理临时文件
rm -f "$SQL_FILE"

log_info "初始化完成!"